package org.smardi.fakeCall.Caller;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.smardi.fakeCall.AC_FakeMain;
import org.smardi.fakeCall.R;
import org.smardi.fakeCall.Setting.SharedPreference_FakeCall;

import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Vibrator;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class AC_FakeCaller extends Activity {

	private boolean isRunning = false; // 진동을 계속 울릴지 결정
	Vibrator vibrator = null;
	Ringtone ringtone = null;

	ImageView img_icon_call = null;
	ImageView img_arrows_green = null;
	ImageView img_arrows_red = null;

	// 통화 버튼/종료버튼
	ImageView btn_connection_start = null;
	ImageView btn_connection_over = null;

	// 통화버튼 눌리면 나타나는 얇은 원
	ImageView img_connection_start_thin = null;
	ImageView img_connection_over_thin = null;

	// 사용자 이름/번호
	TextView txt_caller_name = null;
	TextView txt_caller_number = null;

	// 전화올 때 화면
	RelativeLayout layout_calling = null;
	// 전화 받았을 때 때 화면
	RelativeLayout layout_call_ok = null;
	// 전화 끊었을 때 화면
	RelativeLayout layout_call_end = null;

	//통화 중 통화 시간을 나타내는 텍스트
	TextView txt_time_talk = null;
	
	// 통화 중에 전화를 끊는 버튼
	Button btn_call_over = null;

	SharedPreference_FakeCall mPref = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		//만약 전화 화면을 호출한게 아니라면 FakeCall 메인 페이지를 불러온다

		if(getIntent().getBooleanExtra("calling", false) == false) {
			Intent intent = new Intent(AC_FakeCaller.this, AC_FakeMain.class);
			startActivity(intent);
			finish();
		}
		
		// Window feature for no title - must be set prior to calling
		// setContentView.
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.fakecall_note);

		getWindow().addFlags(
				WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
						| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
						| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
						| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

		// Preference
		mPref = new SharedPreference_FakeCall(AC_FakeCaller.this);

		// 아이콘 설정
		img_icon_call = (ImageView) findViewById(R.id.img_icon_call);
		img_arrows_green = (ImageView) findViewById(R.id.img_arrows_start);
		img_arrows_red = (ImageView) findViewById(R.id.img_arrows_over);
		cTimer_Anim.start();

		// 통화 버튼
		btn_connection_start = (ImageView) findViewById(R.id.btn_connection_start);
		btn_connection_over = (ImageView) findViewById(R.id.btn_connection_over);

		// 통화버튼 눌리면 나타나는 얇은 원
		img_connection_start_thin = (ImageView) findViewById(R.id.img_connection_start_thin);
		img_connection_over_thin = (ImageView) findViewById(R.id.img_connection_over_thin);

		// 사용자 이름/번호
		txt_caller_name = (TextView) findViewById(R.id.txt_caller_name);
		txt_caller_number = (TextView) findViewById(R.id.txt_caller_number);
		txt_caller_name.setText(mPref.getCallerName());
		txt_caller_number.setText(mPref.getCallerNumber());

		// 전화올 때 화면
		layout_calling = (RelativeLayout) findViewById(R.id.layout_calling);
		// 전화 받을 때 화면
		layout_call_ok = (RelativeLayout) findViewById(R.id.layout_call_ok);
		// 전화 끊었을 때 화면
		layout_call_end = (RelativeLayout) findViewById(R.id.layout_call_end);

		//통화 중 통화 시간을 나타내는 텍스트
		txt_time_talk = (TextView)findViewById(R.id.txt_time_talk);
		
		// 통화 중 전화를 끊는 버튼
		btn_call_over = (Button) findViewById(R.id.btn_call_over);
		btn_call_over.setOnClickListener(viewClickListener);

		registEvent();

		// 벨소리 설정
		Uri ringtoneUri = mPref.getRingtoneURI();
		if (ringtoneUri == null) {
			ringtoneUri = RingtoneManager.getActualDefaultRingtoneUri(
					AC_FakeCaller.this, RingtoneManager.TYPE_RINGTONE);
		}
		ringtone = RingtoneManager.getRingtone(AC_FakeCaller.this, ringtoneUri);

		ringtone.setStreamType(AudioManager.STREAM_RING);
		if (mPref.isRingtoneUsable() == true) {
			ringtone.play();
		}

		// 진동 설정
		vibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);

		isRunning = true;
		vibratorThread.start();

	}

	private void registEvent() {
		btn_connection_start.setOnTouchListener(viewTouchListener);
		btn_connection_over.setOnTouchListener(viewTouchListener);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		vibrator.cancel();
		isRunning = false;
		ringtone.stop();
	}
	
	

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch(keyCode) {
		case KeyEvent.KEYCODE_BACK:
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}



	View.OnClickListener viewClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_call_over:
				finish_call();
				break;
			}
		}
	};

	View.OnTouchListener viewTouchListener = new View.OnTouchListener() {

		float x_init = 0f;
		float y_init = 0f;
		float x_end = 0f;
		float y_end = 0f;

		@Override
		public boolean onTouch(View v, MotionEvent event) {

			int action = event.getAction();

			switch (v.getId()) {
			case R.id.btn_connection_start:

				switch (action) {
				case MotionEvent.ACTION_DOWN:
					vibrator.vibrate(200);
					btn_connection_over
							.setImageDrawable(getResources().getDrawable(
									R.drawable.note_icon_connection_over_1));
					btn_connection_over.setBackgroundDrawable(null);
					img_connection_start_thin.setVisibility(View.VISIBLE);
					img_connection_over_thin.setVisibility(View.INVISIBLE);
					img_arrows_red.setVisibility(View.INVISIBLE);

					x_init = event.getRawX();
					y_init = event.getRawY();
					break;
				case MotionEvent.ACTION_UP:
					btn_connection_over.setImageDrawable(getResources()
							.getDrawable(R.drawable.note_icon_connection_over));
					btn_connection_over
							.setBackgroundResource(R.drawable.border_red_circle);
					img_connection_start_thin.setVisibility(View.INVISIBLE);
					img_connection_over_thin.setVisibility(View.INVISIBLE);
					img_arrows_red.setVisibility(View.VISIBLE);
					break;
				case MotionEvent.ACTION_MOVE:
					x_end = event.getRawX();
					y_end = event.getRawY();

					float r = (float) Math.sqrt(Math.pow((x_end - x_init), 2)
							+ Math.pow((y_end - y_init), 2));
					// Log.e("DDD", "r="+r);
					if (200 < r) {
						start_call();
						return false;
					}
					break;
				}

				break;
			case R.id.btn_connection_over:
				switch (action) {
				case MotionEvent.ACTION_DOWN:
					vibrator.vibrate(200);
					btn_connection_start.setImageDrawable(getResources()
							.getDrawable(
									R.drawable.note_icon_connection_start_1));
					btn_connection_start.setBackgroundDrawable(null);
					img_connection_start_thin.setVisibility(View.INVISIBLE);
					img_connection_over_thin.setVisibility(View.VISIBLE);
					img_arrows_green.setVisibility(View.INVISIBLE);

					x_init = event.getRawX();
					y_init = event.getRawY();
					break;
				case MotionEvent.ACTION_UP:
					btn_connection_start
							.setImageDrawable(getResources().getDrawable(
									R.drawable.note_icon_connection_start));
					btn_connection_start
							.setBackgroundResource(R.drawable.border_green_circle);
					img_connection_start_thin.setVisibility(View.INVISIBLE);
					img_connection_over_thin.setVisibility(View.INVISIBLE);
					img_arrows_green.setVisibility(View.VISIBLE);
					break;
				case MotionEvent.ACTION_MOVE:
					x_end = event.getRawX();
					y_end = event.getRawY();

					float r = (float) Math.sqrt(Math.pow((x_end - x_init), 2)
							+ Math.pow((y_end - y_init), 2));

					if (200 < r) {
						finish_call();
						return false;
					}
					break;
				}
				break;
			}

			return true;
		}
	};
	
	private void start_call() {
		ringtone.stop();
		vibrator.cancel();
		isRunning = false;
		
		layout_calling.setVisibility(View.GONE);
		layout_call_ok.setVisibility(View.VISIBLE);
		layout_call_end.setVisibility(View.GONE);
		cTimer_talk.start();
	}

	private void finish_call() {
		ringtone.stop();
		vibrator.cancel();
		isRunning = false;
		
		layout_calling.setVisibility(View.GONE);
		layout_call_ok.setVisibility(View.GONE);
		layout_call_end.setVisibility(View.VISIBLE);
		cTimer_talk.cancel();
		cTimer_end.start();
	}

	/**
	 * 전화오는 동안 애니메이션을 재생 할 타이머
	 */
	CountDownTimer cTimer_Anim = new CountDownTimer(Long.MAX_VALUE, 200) {
		int count = 0;

		@Override
		public void onTick(long millisUntilFinished) {

			int iconDrawable = 0;
			int arrowGreenDrawable = 0;
			int arrowRedDrawable = 0;

			switch (count % 5) {
			case 0:
				iconDrawable = R.drawable.note_icon_call_4;
				break;
			case 1:
				iconDrawable = R.drawable.note_icon_call_3;
				break;
			case 2:
				iconDrawable = R.drawable.note_icon_call_2;
				break;
			case 3:
				iconDrawable = R.drawable.note_icon_call_1;
				break;
			case 4:
				iconDrawable = R.drawable.note_icon_call_0;
				break;
			}

			switch (count % 3) {
			case 0:
				arrowGreenDrawable = R.drawable.note_arrows_green_0;
				arrowRedDrawable = R.drawable.note_arrows_red_0;
				break;
			case 1:
				arrowGreenDrawable = R.drawable.note_arrows_green_1;
				arrowRedDrawable = R.drawable.note_arrows_red_1;
				break;
			case 2:
				arrowGreenDrawable = R.drawable.note_arrows_green_2;
				arrowRedDrawable = R.drawable.note_arrows_red_2;
				break;
			}

			img_icon_call.setImageDrawable(getResources().getDrawable(
					iconDrawable));
			img_arrows_green.setImageDrawable(getResources().getDrawable(
					arrowGreenDrawable));
			img_arrows_red.setImageDrawable(getResources().getDrawable(
					arrowRedDrawable));
			count++;
		}

		@Override
		public void onFinish() {
			// TODO Auto-generated method stub

		}
	};
	
	/**
	 * 전화를 받았을 때 타이머
	 * 통화시간을 표시한다
	 */
	CountDownTimer cTimer_talk = new CountDownTimer(Long.MAX_VALUE, 100) {
		
		SimpleDateFormat dFormat = new SimpleDateFormat("mm:ss");
		long time_last = 0;
		long time_now = 0;
		
		
		@Override
		public void onTick(long millisUntilFinished) {
			if(time_last == 0) {
				time_last = time_now;
			}
			
			time_now = new Date().getTime();
			String time = dFormat.format(new Date(time_now - time_last));
			txt_time_talk.setText(time);
		}
		
		@Override
		public void onFinish() {
			//없음 
		}
	};
	
	/**
	 * 전화를 끊었을 때 타이머 "통화 종료" 라는 맨트를 깜빡이게 한다
	 */
	CountDownTimer cTimer_end = new CountDownTimer(2500, 100) {

		String x_message = "";
		long time_last_run = 0;
		long time_now = 0;

		@Override
		public void onTick(long millisUntilFinished) {
			time_now = new Date().getTime();

			if (time_last_run == 0) {
				time_last_run = time_now;
			}

			if (500 < time_now - time_last_run) {
				TextView txt_call_end = (TextView) findViewById(R.id.txt_end);
				if (txt_call_end.getText().toString().equals("") == true) {
					// 값이 비어있을 때에는 예전 메시지를 넣는다
					txt_call_end.setText(x_message);
				} else {
					x_message = txt_call_end.getText().toString();
					txt_call_end.setText("");
				}

				time_last_run = time_now;
			}
		}

		@Override
		public void onFinish() {
			// 전화 앱을 끝낸다
			finish();
		}
	};

	Thread vibratorThread = new Thread(new Runnable() {
		@Override
		public void run() {
			while (isRunning) {

				if (mPref.isVibratorUsable() == true) {
					vibrator.vibrate(1000);
				}
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}
		}
	});
}
